import React, { PureComponent } from "react";
import { View, StyleSheet, SafeAreaView, Text, TextInput, ActivityIndicator, DeviceEventEmitter } from "react-native";
import { Button, Icon, Overlay } from "react-native-tengits-elements";
import Swiper from "react-native-tengits-swiper";
import { TText } from "../common/Widgets/WidgetDefault";
import DataCenter from "../logic/DataCenter";
import { TNormalExceptCircle, TNumberCircle, TUpDownText } from "./Components/NormalExceptCircle";
import { OverlayGateSelectList } from "./Components/GateSelectList";
import { Colors, FontSize } from "../common/Theme/TTheme";
import { scaleSize } from "../common/Utils/ToolUtils";
import CommonDrawer from "../common/Widgets/CommonDrawer";
import { onlineStatus } from "../logic/LogicConstant";
import { OnlineStatusComponent } from "./Components/SubItemComponent";

export default class DeviceRunningSummaryPage extends React.PureComponent {
    constructor(props) {
        super(props);
        let data = [DataCenter.getLocalCabinetData(), ...DataCenter.getColonyExceptLocalCabinetData()];
        this.state = {
            index:0,
            colonyCabinet: data,
            selectDeviceVisible: false,
            online: data[0].onlineStatus,
        };
    }

    componentDidMount() {
        this.localCabinetListener = DeviceEventEmitter.addListener("localCabinet", this.updateState.bind(this));
        this.colonyCabinetListener = DeviceEventEmitter.addListener("colonyCabinet", this.updateState.bind(this));
    }

    updateState() {
        console.log("update State");
        let data = [DataCenter.getLocalCabinetData(), ...DataCenter.getColonyExceptLocalCabinetData()];
        let lastIndex = this.state.index;
        if(lastIndex >= data.length){
            lastIndex = Math.min(lastIndex, data.length - 1);
        }
        this.setState({
            colonyCabinet: data,
            index: lastIndex,
            online: data[lastIndex].onlineStatus,
        });
    }

    componentWillUnmount() {
        this.localCabinetListener.remove();
        this.colonyCabinetListener.remove();
    }

    getHeadTitle = ()=>{
        const{index, colonyCabinet} = this.state;
        let baseName = DataCenter.getTunnleBaseInfo();
        return baseName + (colonyCabinet[index]?.gateName ? colonyCabinet[index]?.gateName : "");
    }

    renderHeader() {
        const{index, colonyCabinet, online} = this.state;
        return <View style={styles.header}>
                <Button 
                    buttonStyle={{borderRadius:0, backgroundColor:Colors.button_color, width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon name='menu' color={Colors.white} size={scaleSize(40)}/>}
                    onPress={()=>{
                        this.selectDrawer && this.selectDrawer.showModalAnimate()
                }}/>
                <View style={{flex:1, flexDirection:'row', alignItems:'center', justifyContent:'center'}}>
                {index > 0 ? <Button 
                    buttonStyle={{backgroundColor:'transparent', width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon size={scaleSize(40)} name='chevron-left' type='font-awesome' color={Colors.white}/>}
                    onPress={()=>{
                        let ret = Math.max(0, index-1);
                        this.setState({index: ret, online: colonyCabinet[ret].onlineStatus});
                }}/> : null}
                <View style={{flex:1, alignItems:'center', flexDirection:'row', justifyContent:'center'}}>
                <Text style={{fontSize: FontSize.h3_font, color:Colors.white}}>{`${this.getHeadTitle()}`}</Text>
                {index == 0 ? <View style={{alignItems:'center', justifyContent:'center', marginLeft: scaleSize(20), width:scaleSize(100), borderRadius:scaleSize(6), height:scaleSize(40), backgroundColor: Colors.calm_color}}>
                    <Text style={{fontSize: FontSize.h4_font, color:Colors.white}}>
                        {"本柜"}</Text>
                    </View> : <View style={{alignItems:'center', justifyContent:'center', borderRadius:scaleSize(6), marginLeft: scaleSize(20), width:scaleSize(100), height:scaleSize(40), backgroundColor: "#FFAB2D"}}>
                    <Text style={{fontSize: FontSize.h4_font, color:Colors.white}}>
                        {"非本柜"}</Text>
                    </View>}
                    {online == onlineStatus.OFFLINE ?  <OnlineStatusComponent isOnline={false} containerStyle={{marginLeft: scaleSize(12)}}/> : null}
                </View>
                {index < (colonyCabinet||[]).length - 1 ? <Button
                    buttonStyle={{backgroundColor:'transparent', width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon size={scaleSize(40)} name='chevron-right' type='font-awesome' color={Colors.white}/>}
                    onPress={()=>{
                        let ret = Math.min((colonyCabinet||[]).length - 1, index+1);
                        this.setState({index: ret, online: colonyCabinet[ret].onlineStatus});
                    }}
                    /> : null}
            </View>
            <Button 
                    buttonStyle={{borderRadius:0, backgroundColor:Colors.button_color, width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon name='sync-alt' type='MaterialIcons' color={Colors.white} size={scaleSize(40)}/>}
                    onPress={()=>{
                        this.setState({selectDeviceVisible: true});
                }}/>
        </View>
    }

    toggleOverlay = (key) => {
        if(key == "GateSelect") {
            this.setState({selectDeviceVisible: false});
        }
    }

    onSure = (key, params) => {
        const{colonyCabinet} = this.state;
        if(key == "GateSelect") {
            this.setState({index: params},()=>{
                this.setState({selectDeviceVisible: false,
                    online: colonyCabinet[params].onlineStatus,
                    });
            });
        } 
    }

    renderMenuDrawer() {
        const{navigation} = this.props;
        return <View style={{flex:1, flexDirection:'column', paddingHorizontal:scaleSize(44)}}>
                <Button buttonStyle={{height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"本控制柜管控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('Main');
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"集群控制柜管控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('Colony');
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"单洞分段调控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('SingleHole');
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"控制柜运行概览"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"设备信息"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('DeviceInfo');
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"注册管理"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('RegisterDevice');
                }}/>
            </View>
    }

    render() {
        const{index, colonyCabinet, selectDeviceVisible} = this.state;
        return <SafeAreaView style={styles.container}>
                {this.renderHeader()}
                <View style={{flex:1, backgroundColor: index == 0 ? Colors.page_bg_color : Colors.page_bg_color1}}>
                <Swiper index={index} showsButtons={false} 
                        loop={false} autoplay={false} 
                        showsPagination={false} scrollEnabled={false}>
                        {(colonyCabinet||[]).map((item, index)=>{
                            return <SubPage data={item} 
                            key={"run_sub_" + index}/>
                    })}
                </Swiper>
                </View>
                <CommonDrawer ref={(r) => {
                        this.selectDrawer = r;
                    }} contentView={this.renderMenuDrawer()}/>
                <Overlay overlayStyle={{padding:0}} isVisible={selectDeviceVisible} onBackdropPress={()=>{this.toggleOverlay("GateSelect")}} fullScreen>
                    <OverlayGateSelectList data={colonyCabinet} 
                    index={index}
                    localIndex={0}
                    toggleOverlay={this.toggleOverlay} onSure={this.onSure}/>
                </Overlay>
            </SafeAreaView>
    }
}

const SubPage = (props) => {
    return <View style={{flex:1, paddingHorizontal: scaleSize(46), paddingVertical: scaleSize(30)}}>
        <View style={[styles.cardContainer, {height:scaleSize(188)}]}>
            <View style={{height:scaleSize(50), justifyContent:'center', alignItems:'center', borderRadius: scaleSize(6), backgroundColor: Colors.button_color}}>
            <Text style={{fontSize: FontSize.h4_font, color: Colors.white}}>{"能耗（wh）"}</Text>
            </View>
            <View style={{flexDirection:'row', height:scaleSize(138), justifyContent:'space-around', alignItems:'center'}}>
            <TUpDownText title={"加强段1"} number={"--"}/> 
            <TUpDownText title={"加强段2"} number={"--"}/> 
            <TUpDownText title={"过渡段1"} number={"--"}/> 
            <TUpDownText title={"过渡段2"} number={"--"}/> 
            </View>
        </View>
        <View style={{flex:1, flexDirection:'row', marginTop:scaleSize(22)}}>
            <View style={{flex:1, flexDirection:'column'}}>
                <View style={[styles.cardContainer,{height:scaleSize(222)}]}>
                    <View style={{height:scaleSize(50), justifyContent:'center', alignItems:'center', borderRadius: scaleSize(6), backgroundColor: Colors.button_color}}>
                    <Text style={{fontSize: FontSize.h4_font, color: Colors.white}}>{"光强/光照"}</Text>
                    </View>
                    <View style={{flexDirection:'row', paddingVertical: scaleSize(20), justifyContent:'space-around', alignItems:'center'}}>
                        <TNumberCircle title={"洞内光强"} number={"--"} bgColor={Colors.perple_color}/>
                        <TNumberCircle title={"洞外光强"} number={"--"} bgColor={Colors.blue_color}/>
                    </View>
                </View>
                <View style={[styles.cardContainer,{marginTop:scaleSize(20), height: scaleSize(194)}]}>
                    <View style={{height:scaleSize(50), justifyContent:'center', alignItems:'center', borderRadius: scaleSize(6), backgroundColor: Colors.button_color}}>
                    <Text style={{fontSize: FontSize.h4_font, color: Colors.white}}>{"车流量"}</Text>
                    </View>
                    <View style={{flexDirection:'row', height:scaleSize(132), paddingVertical: scaleSize(20), justifyContent:'space-around', alignItems:'center'}}>
                        <TUpDownText title={"车检器1"} number={"--"}/> 
                        <TUpDownText title={"车检器2"} number={"--"}/> 
                    </View>
                </View>
            </View>
            <View style={[styles.cardContainer, {flex:1, marginLeft:scaleSize(27)}]}>
                <View style={{height:scaleSize(50), justifyContent:'center', alignItems:'center', borderRadius: scaleSize(6), backgroundColor: Colors.button_color}}>
                    <Text style={{fontSize: FontSize.h4_font, color: Colors.white}}>{"控制柜内设备状态"}</Text>
                </View>
                <View style={{flexDirection:'row', flexWrap:'wrap', alignItems:'center', justifyContent:'flex-start'}}>
                    <TNormalExceptCircle containerStyle={styles.normalExceptContainer} title={"服务端连接"} normal={props.data.onlineStatus == onlineStatus.ONLINE}/>
                    <TNormalExceptCircle containerStyle={styles.normalExceptContainer} title={"回路控制器"} normal={true}/>
                    <TNormalExceptCircle containerStyle={styles.normalExceptContainer} title={"智能电表"} normal={true}/>
                    <TNormalExceptCircle containerStyle={styles.normalExceptContainer} normalText={"--"} title={"光强检测器"} normal={true}/>
                    <TNormalExceptCircle containerStyle={styles.normalExceptContainer} normalText={"--"} title={"车检器"} normal={true}/>
                </View>
            </View>
        </View>
    </View>
}

const styles = StyleSheet.create({
    container:{
        flex:1,  
        justifyContent:'space-around'
    },
    header:{
        flexDirection: 'row',
        height: scaleSize(88),
        backgroundColor: Colors.navibar_color,
    },
    cardContainer:{
        flexDirection:'column',
        backgroundColor: Colors.white,
        borderRadius: scaleSize(6),
    },
    normalExceptContainer:{
        width:scaleSize(200), 
        paddingVertical:scaleSize(10), 
        paddingHorizontal:scaleSize(0), 
        marginVertical:scaleSize(10)
    },
});